package cn.mldn.eshop.datasync.rabbitmq;

import cn.mldn.eshop.datasync.service.EshopProductService;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.*;

@Component
@RabbitListener(queues = "data-change-queue")
public class DataChangeQueueReceiver {
    public DataChangeQueueReceiver() {
        new Thread(new MyThread()).start();
    }

    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String,String> redisTemplate ;
    @Resource
    private EshopProductService eshopProductService ;
    @Resource
    private RabbitMQSender rabbitMQSender ;
    private Set<String> messageSet = Collections.synchronizedSet(new HashSet<>()) ;
    private List<JSONObject> brandDataChangeMessageList = new ArrayList<JSONObject>();
    @RabbitHandler
    public void process(String message) {
        System.out.println("xxx");
        // 对这个message进行解析
        JSONObject jsonObject = JSONObject.parseObject(message);

        // 先获取data_type
        String dataType = jsonObject.getString("data_type");
        if("brand".equals(dataType)) {
            processBrandDataChangeMessage(jsonObject);
        } else if("category".equals(dataType)) {
            processCategoryDataChangeMessage(jsonObject);
        } else if("product_intro".equals(dataType)) {
            processProductIntroDataChangeMessage(jsonObject);
        } else if("product_property".equals(dataType)) {
            processProductPropertyDataChangeMessage(jsonObject);
        } else if("product".equals(dataType)) {
            processProductDataChangeMessage(jsonObject);
        } else if("product_specification".equals(dataType)) {
            processProductSpecificationDataChangeMessage(jsonObject);
        }
    }
    private void processBrandDataChangeMessage(JSONObject messageJSONObject){
        long id = messageJSONObject.getLong("id") ;
        String eventType = messageJSONObject.getString("event_type") ;
        if(eventType.equals("add")||eventType.equals("update")){
            brandDataChangeMessageList.add(messageJSONObject) ;
            if(brandDataChangeMessageList.size()>=2){
                String ids = "" ;
                for(int i = 0 ;i<brandDataChangeMessageList.size() ; i++){
                    ids += brandDataChangeMessageList.get(i).getLong("id") ;
                    if(i<this.brandDataChangeMessageList.size()-1){
                        ids+="," ;
                    }
                }
                JSONArray dataJSONArray = JSONArray.parseArray(this.eshopProductService.findBrandByIds(ids)) ;
                for(int j = 0; j<dataJSONArray.size() ; j++){
                    JSONObject dataJSONObject = dataJSONArray.getJSONObject(j) ;
                    this.redisTemplate.opsForValue().set("brand_"+dataJSONObject.getLong("id"),dataJSONObject.toJSONString());
                    this.messageSet.add("{\"dim_type\": \"brand\", \"id\": " + dataJSONObject.getLong("id") + "}") ;
                }
                brandDataChangeMessageList.clear();

            }

        }
        else if(eventType.equals("delete")){
            this.redisTemplate.delete("brand_"+id);
            this.messageSet.add("{\"dim_type\": \"brand\", \"id\": " + id + "}") ;
        }

    }
    private void processCategoryDataChangeMessage(JSONObject messageJSONObject){
        long id = messageJSONObject.getLong("id") ;
        String eventType = messageJSONObject.getString("event_type") ;
        if(eventType.equals("add")||eventType.equals("update")){
            JSONObject dataJSONObject = JSONObject.parseObject(this.eshopProductService.findCategoryById(id)) ;
            this.redisTemplate.opsForValue().set("category_"+id,dataJSONObject.toJSONString());
        }
        else if(eventType.equals("delete")){
            this.redisTemplate.delete("category_"+id);
        }
        this.messageSet.add("{\"dim_type\": \"category\", \"id\": " + id + "}") ;

    }
    private void processProductDataChangeMessage(JSONObject messageJSONObject){
        long id = messageJSONObject.getLong("id") ;
        String eventType = messageJSONObject.getString("event_type") ;
        if(eventType.equals("add")||eventType.equals("update")){
            JSONObject dataJSONObject = JSONObject.parseObject(this.eshopProductService.findProductById(id)) ;
            this.redisTemplate.opsForValue().set("product_"+id,dataJSONObject.toJSONString());
        }
        else if(eventType.equals("delete")){
            this.redisTemplate.delete("product_"+id);
        }
        this.messageSet.add("{\"dim_type\": \"product\", \"id\": " + id + "}") ;

    }
    private void processProductIntroDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        Long productId = messageJSONObject.getLong("product_id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductIntroById(id));

            this.redisTemplate.opsForValue().set("product_intro_" + productId, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {

            this.redisTemplate.delete("product_intro_" + productId);
        }
        this.messageSet.add("{\"dim_type\": \"product_intro\", \"id\": " + productId + "}") ;

    }

    private void processProductPropertyDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        Long productId = messageJSONObject.getLong("product_id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductPropertyById(id));
            this.redisTemplate.opsForValue().set("product_property_" + productId, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            this.redisTemplate.delete("product_property_" + productId);
        }
        this.messageSet.add("{\"dim_type\": \"product\", \"id\": " + productId + "}") ;
    }

    private void processProductSpecificationDataChangeMessage(JSONObject messageJSONObject) {
        Long id = messageJSONObject.getLong("id");
        Long productId = messageJSONObject.getLong("product_id");
        String eventType = messageJSONObject.getString("event_type");

        if("add".equals(eventType) || "update".equals(eventType)) {
            JSONObject dataJSONObject = JSONObject.parseObject(eshopProductService.findProductSpecificationById(id));
            this.redisTemplate.opsForValue().set("product_specification_" + productId, dataJSONObject.toJSONString());
        } else if ("delete".equals(eventType)) {
            this.redisTemplate.delete("product_specification_" + productId);
        }
        this.messageSet.add("{\"dim_type\": \"product\", \"id\": " + productId + "}") ;

    }
    private class  MyThread implements  Runnable{

        @Override
        public void run() {
            while (true){
                if (!messageSet.isEmpty()){
                    for(String message:messageSet){
                        rabbitMQSender.send("aggr-data-change-queue", message);
                    }
                    messageSet.clear();
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


}
